from django.shortcuts import render,HttpResponse
from .models import User, Article
from datetime import datetime
# Create your views here.
def article_test(request):
    user = User(name='高小博',age='19')
    user.save()
    article = Article(title='明月不常有', content='人工智能', author=user)
    article.save()
    # article = Article.objects.first()
    # print(article.author.name)
    return HttpResponse(article.author.name)
def one_to_many(request):
    user = User.objects.first()
    # articles = user.articles.all()
    articles = user.articles.filter(title__contains='明').all()
    for article in articles:
        print(article.title)
    return HttpResponse('ok')

# 查找操作
# exact:精确差找
def query_set(request):
    articletwo = Article.objects.filter(id__exact=1)
    # 查询结果.query看到.article.query,就可以看到底层执行的sql语句
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
# iexact:不区分大小写
def query_iexact(request):
    articletwo = Article.objects.filter(title__iexact='明月不常有')
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
# contains:区分大小写 ,模糊查询
def query_contains(request):
    articletwo = Article.objects.filter(title__contains='明')
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
# icontains:不区分大小写
def query_icontains(request):
    articletwo = Article.objects.filter(title__icontains='明')
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
# in:在范围内
def query_in(request):
    articletwo = Article.objects.filter(id__in=[1,2,3])
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
def query_range(request):
    start_date = datetime(year=2025,month=1,day=1)
    end_date = datetime(year=2025,month=1,day=14,hour=23,minute=59,second=59)
    articletwo = Article.objects.filter(pub_time__range=(start_date,end_date))
    print(articletwo.query)
    print(articletwo)
    return HttpResponse('ok')
# sql中的联合查询(内连接)：从查找标题中，包含”明月“文章的用户
def query_sql(request):
    user = User.objects.filter(articles__title__contains='明月')
    print(user.query)
    print(user)
    return HttpResponse('ok')

